{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Live Human Pose Estimation with OpenVINO™\n",
    "\n",
    "This notebook demonstrates live pose estimation with OpenVINO, using the OpenPose [human-pose-estimation-0001](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001) model from [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). Final part of this notebook shows live inference results from a webcam. Additionally, you can also upload a video file.\n",
    "\n",
    "> **NOTE**: To use a webcam, you must run this Jupyter notebook on a computer with a webcam. If you run on a server, the webcam will not work. However, you can still do inference on a video in the final step.\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Imports](#Imports)\n",
    "- [The model](#The-model)\n",
    "    - [Download the model](#Download-the-model)\n",
    "    - [Load the model](#Load-the-model)\n",
    "- [Processing](#Processing)\n",
    "    - [OpenPose Decoder](#OpenPose-Decoder)\n",
    "    - [Process Results](#Process-Results)\n",
    "    - [Draw Pose Overlays](#Draw-Pose-Overlays)\n",
    "    - [Main Processing Function](#Main-Processing-Function)\n",
    "- [Run](#Run)\n",
    "    - [Run Live Pose Estimation](#Run-Live-Pose-Estimation)\n",
    "\n",
    "\n",
    "### Installation Instructions\n",
    "\n",
    "This is a self-contained example that relies solely on its own code.\n",
    "\n",
    "We recommend  running the notebook in a virtual environment. You only need a Jupyter server to start.\n",
    "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide).\n",
    "\n",
    "<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=5b5a4db0-7875-4bfb-bdbd-01698b5b1a77&file=notebooks/pose-estimation-webcam/pose-estimation.ipynb\" />\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"openvino>=2023.1.0\" opencv-python tqdm"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import time\n",
    "from pathlib import Path\n",
    "\n",
    "import cv2\n",
    "import numpy as np\n",
    "from IPython import display\n",
    "from numpy.lib.stride_tricks import as_strided\n",
    "import openvino as ov\n",
    "\n",
    "# Fetch `notebook_utils` module\n",
    "import requests\n",
    "\n",
    "if not Path(\"notebook_utils.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    "    )\n",
    "\n",
    "    open(\"notebook_utils.py\", \"w\").write(r.text)\n",
    "\n",
    "import notebook_utils as utils\n",
    "\n",
    "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n",
    "from notebook_utils import collect_telemetry\n",
    "\n",
    "collect_telemetry(\"pose-estimation.ipynb\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Download the model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Use the `download_file`, a function from the `notebook_utils` file. It automatically creates a directory structure and downloads the selected model.\n",
    "\n",
    "If you want to download another model, replace the name of the model and precision in the code below. \n",
    "\n",
    "> **NOTE**: This may require a different pose decoder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# A directory where the model will be downloaded.\n",
    "base_model_dir = Path(\"model\")\n",
    "\n",
    "# The name of the model from Open Model Zoo.\n",
    "model_name = \"human-pose-estimation-0001\"\n",
    "# Selected precision (FP32, FP16, FP16-INT8).\n",
    "precision = \"FP16-INT8\"\n",
    "\n",
    "model_path = base_model_dir / \"intel\" / model_name / precision / f\"{model_name}.xml\"\n",
    "\n",
    "if not model_path.exists():\n",
    "    model_url_dir = f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2022.1/models_bin/3/{model_name}/{precision}/\"\n",
    "    utils.download_file(model_url_dir + model_name + \".xml\", model_path.name, model_path.parent)\n",
    "    utils.download_file(\n",
    "        model_url_dir + model_name + \".bin\",\n",
    "        model_path.with_suffix(\".bin\").name,\n",
    "        model_path.parent,\n",
    "    )"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Downloaded models are located in a fixed structure, which indicates a vendor, the name of the model and a precision.\n",
    "\n",
    "Only a few lines of code are required to run the model. First, initialize OpenVINO Runtime. Then, read the network architecture and model weights from the `.bin` and `.xml` files to compile it for the desired device. Select device from dropdown list for running inference using OpenVINO."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = utils.device_widget()\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openvino.properties.hint as hints\n",
    "\n",
    "\n",
    "# Initialize OpenVINO Runtime\n",
    "core = ov.Core()\n",
    "# Read the network from a file.\n",
    "model = core.read_model(model_path)\n",
    "# Let the AUTO device decide where to load the model (you can use CPU, GPU as well).\n",
    "compiled_model = core.compile_model(model=model, device_name=device.value, config={hints.performance_mode(): hints.PerformanceMode.LATENCY})\n",
    "\n",
    "# Get the input and output names of nodes.\n",
    "input_layer = compiled_model.input(0)\n",
    "output_layers = compiled_model.outputs\n",
    "\n",
    "# Get the input size.\n",
    "height, width = list(input_layer.shape)[2:]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Input layer has the name of the input node and output layers contain names of output nodes of the network. In the case of OpenPose Model, there is 1 input and 2 outputs: PAFs and keypoints heatmap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_layer.any_name, [o.any_name for o in output_layers]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### OpenPose Decoder\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "To transform the raw results from the neural network into pose estimations, you need OpenPose Decoder. It is provided in the [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/openvino/model_zoo/model_api/models/open_pose.py) and compatible with the `human-pose-estimation-0001` model.\n",
    "\n",
    "If you choose a model other than `human-pose-estimation-0001` you will need another decoder (for example, `AssociativeEmbeddingDecoder`), which is available in the [demos section](https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/openvino/model_zoo/model_api/models/hpe_associative_embedding.py) of Open Model Zoo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# code from https://github.com/openvinotoolkit/open_model_zoo/blob/9296a3712069e688fe64ea02367466122c8e8a3b/demos/common/python/models/open_pose.py#L135\n",
    "class OpenPoseDecoder:\n",
    "    BODY_PARTS_KPT_IDS = (\n",
    "        (1, 2),\n",
    "        (1, 5),\n",
    "        (2, 3),\n",
    "        (3, 4),\n",
    "        (5, 6),\n",
    "        (6, 7),\n",
    "        (1, 8),\n",
    "        (8, 9),\n",
    "        (9, 10),\n",
    "        (1, 11),\n",
    "        (11, 12),\n",
    "        (12, 13),\n",
    "        (1, 0),\n",
    "        (0, 14),\n",
    "        (14, 16),\n",
    "        (0, 15),\n",
    "        (15, 17),\n",
    "        (2, 16),\n",
    "        (5, 17),\n",
    "    )\n",
    "    BODY_PARTS_PAF_IDS = (\n",
    "        12,\n",
    "        20,\n",
    "        14,\n",
    "        16,\n",
    "        22,\n",
    "        24,\n",
    "        0,\n",
    "        2,\n",
    "        4,\n",
    "        6,\n",
    "        8,\n",
    "        10,\n",
    "        28,\n",
    "        30,\n",
    "        34,\n",
    "        32,\n",
    "        36,\n",
    "        18,\n",
    "        26,\n",
    "    )\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_joints=18,\n",
    "        skeleton=BODY_PARTS_KPT_IDS,\n",
    "        paf_indices=BODY_PARTS_PAF_IDS,\n",
    "        max_points=100,\n",
    "        score_threshold=0.1,\n",
    "        min_paf_alignment_score=0.05,\n",
    "        delta=0.5,\n",
    "    ):\n",
    "        self.num_joints = num_joints\n",
    "        self.skeleton = skeleton\n",
    "        self.paf_indices = paf_indices\n",
    "        self.max_points = max_points\n",
    "        self.score_threshold = score_threshold\n",
    "        self.min_paf_alignment_score = min_paf_alignment_score\n",
    "        self.delta = delta\n",
    "\n",
    "        self.points_per_limb = 10\n",
    "        self.grid = np.arange(self.points_per_limb, dtype=np.float32).reshape(1, -1, 1)\n",
    "\n",
    "    def __call__(self, heatmaps, nms_heatmaps, pafs):\n",
    "        batch_size, _, h, w = heatmaps.shape\n",
    "        assert batch_size == 1, \"Batch size of 1 only supported\"\n",
    "\n",
    "        keypoints = self.extract_points(heatmaps, nms_heatmaps)\n",
    "        pafs = np.transpose(pafs, (0, 2, 3, 1))\n",
    "\n",
    "        if self.delta > 0:\n",
    "            for kpts in keypoints:\n",
    "                kpts[:, :2] += self.delta\n",
    "                np.clip(kpts[:, 0], 0, w - 1, out=kpts[:, 0])\n",
    "                np.clip(kpts[:, 1], 0, h - 1, out=kpts[:, 1])\n",
    "\n",
    "        pose_entries, keypoints = self.group_keypoints(keypoints, pafs, pose_entry_size=self.num_joints + 2)\n",
    "        poses, scores = self.convert_to_coco_format(pose_entries, keypoints)\n",
    "        if len(poses) > 0:\n",
    "            poses = np.asarray(poses, dtype=np.float32)\n",
    "            poses = poses.reshape((poses.shape[0], -1, 3))\n",
    "        else:\n",
    "            poses = np.empty((0, 17, 3), dtype=np.float32)\n",
    "            scores = np.empty(0, dtype=np.float32)\n",
    "\n",
    "        return poses, scores\n",
    "\n",
    "    def extract_points(self, heatmaps, nms_heatmaps):\n",
    "        batch_size, channels_num, h, w = heatmaps.shape\n",
    "        assert batch_size == 1, \"Batch size of 1 only supported\"\n",
    "        assert channels_num >= self.num_joints\n",
    "\n",
    "        xs, ys, scores = self.top_k(nms_heatmaps)\n",
    "        masks = scores > self.score_threshold\n",
    "        all_keypoints = []\n",
    "        keypoint_id = 0\n",
    "        for k in range(self.num_joints):\n",
    "            # Filter low-score points.\n",
    "            mask = masks[0, k]\n",
    "            x = xs[0, k][mask].ravel()\n",
    "            y = ys[0, k][mask].ravel()\n",
    "            score = scores[0, k][mask].ravel()\n",
    "            n = len(x)\n",
    "            if n == 0:\n",
    "                all_keypoints.append(np.empty((0, 4), dtype=np.float32))\n",
    "                continue\n",
    "            # Apply quarter offset to improve localization accuracy.\n",
    "            x, y = self.refine(heatmaps[0, k], x, y)\n",
    "            np.clip(x, 0, w - 1, out=x)\n",
    "            np.clip(y, 0, h - 1, out=y)\n",
    "            # Pack resulting points.\n",
    "            keypoints = np.empty((n, 4), dtype=np.float32)\n",
    "            keypoints[:, 0] = x\n",
    "            keypoints[:, 1] = y\n",
    "            keypoints[:, 2] = score\n",
    "            keypoints[:, 3] = np.arange(keypoint_id, keypoint_id + n)\n",
    "            keypoint_id += n\n",
    "            all_keypoints.append(keypoints)\n",
    "        return all_keypoints\n",
    "\n",
    "    def top_k(self, heatmaps):\n",
    "        N, K, _, W = heatmaps.shape\n",
    "        heatmaps = heatmaps.reshape(N, K, -1)\n",
    "        # Get positions with top scores.\n",
    "        ind = heatmaps.argpartition(-self.max_points, axis=2)[:, :, -self.max_points :]\n",
    "        scores = np.take_along_axis(heatmaps, ind, axis=2)\n",
    "        # Keep top scores sorted.\n",
    "        subind = np.argsort(-scores, axis=2)\n",
    "        ind = np.take_along_axis(ind, subind, axis=2)\n",
    "        scores = np.take_along_axis(scores, subind, axis=2)\n",
    "        y, x = np.divmod(ind, W)\n",
    "        return x, y, scores\n",
    "\n",
    "    @staticmethod\n",
    "    def refine(heatmap, x, y):\n",
    "        h, w = heatmap.shape[-2:]\n",
    "        valid = np.logical_and(np.logical_and(x > 0, x < w - 1), np.logical_and(y > 0, y < h - 1))\n",
    "        xx = x[valid]\n",
    "        yy = y[valid]\n",
    "        dx = np.sign(heatmap[yy, xx + 1] - heatmap[yy, xx - 1], dtype=np.float32) * 0.25\n",
    "        dy = np.sign(heatmap[yy + 1, xx] - heatmap[yy - 1, xx], dtype=np.float32) * 0.25\n",
    "        x = x.astype(np.float32)\n",
    "        y = y.astype(np.float32)\n",
    "        x[valid] += dx\n",
    "        y[valid] += dy\n",
    "        return x, y\n",
    "\n",
    "    @staticmethod\n",
    "    def is_disjoint(pose_a, pose_b):\n",
    "        pose_a = pose_a[:-2]\n",
    "        pose_b = pose_b[:-2]\n",
    "        return np.all(np.logical_or.reduce((pose_a == pose_b, pose_a < 0, pose_b < 0)))\n",
    "\n",
    "    def update_poses(\n",
    "        self,\n",
    "        kpt_a_id,\n",
    "        kpt_b_id,\n",
    "        all_keypoints,\n",
    "        connections,\n",
    "        pose_entries,\n",
    "        pose_entry_size,\n",
    "    ):\n",
    "        for connection in connections:\n",
    "            pose_a_idx = -1\n",
    "            pose_b_idx = -1\n",
    "            for j, pose in enumerate(pose_entries):\n",
    "                if pose[kpt_a_id] == connection[0]:\n",
    "                    pose_a_idx = j\n",
    "                if pose[kpt_b_id] == connection[1]:\n",
    "                    pose_b_idx = j\n",
    "            if pose_a_idx < 0 and pose_b_idx < 0:\n",
    "                # Create new pose entry.\n",
    "                pose_entry = np.full(pose_entry_size, -1, dtype=np.float32)\n",
    "                pose_entry[kpt_a_id] = connection[0]\n",
    "                pose_entry[kpt_b_id] = connection[1]\n",
    "                pose_entry[-1] = 2\n",
    "                pose_entry[-2] = np.sum(all_keypoints[connection[0:2], 2]) + connection[2]\n",
    "                pose_entries.append(pose_entry)\n",
    "            elif pose_a_idx >= 0 and pose_b_idx >= 0 and pose_a_idx != pose_b_idx:\n",
    "                # Merge two poses are disjoint merge them, otherwise ignore connection.\n",
    "                pose_a = pose_entries[pose_a_idx]\n",
    "                pose_b = pose_entries[pose_b_idx]\n",
    "                if self.is_disjoint(pose_a, pose_b):\n",
    "                    pose_a += pose_b\n",
    "                    pose_a[:-2] += 1\n",
    "                    pose_a[-2] += connection[2]\n",
    "                    del pose_entries[pose_b_idx]\n",
    "            elif pose_a_idx >= 0 and pose_b_idx >= 0:\n",
    "                # Adjust score of a pose.\n",
    "                pose_entries[pose_a_idx][-2] += connection[2]\n",
    "            elif pose_a_idx >= 0:\n",
    "                # Add a new limb into pose.\n",
    "                pose = pose_entries[pose_a_idx]\n",
    "                if pose[kpt_b_id] < 0:\n",
    "                    pose[-2] += all_keypoints[connection[1], 2]\n",
    "                pose[kpt_b_id] = connection[1]\n",
    "                pose[-2] += connection[2]\n",
    "                pose[-1] += 1\n",
    "            elif pose_b_idx >= 0:\n",
    "                # Add a new limb into pose.\n",
    "                pose = pose_entries[pose_b_idx]\n",
    "                if pose[kpt_a_id] < 0:\n",
    "                    pose[-2] += all_keypoints[connection[0], 2]\n",
    "                pose[kpt_a_id] = connection[0]\n",
    "                pose[-2] += connection[2]\n",
    "                pose[-1] += 1\n",
    "        return pose_entries\n",
    "\n",
    "    @staticmethod\n",
    "    def connections_nms(a_idx, b_idx, affinity_scores):\n",
    "        # From all retrieved connections that share starting/ending keypoints leave only the top-scoring ones.\n",
    "        order = affinity_scores.argsort()[::-1]\n",
    "        affinity_scores = affinity_scores[order]\n",
    "        a_idx = a_idx[order]\n",
    "        b_idx = b_idx[order]\n",
    "        idx = []\n",
    "        has_kpt_a = set()\n",
    "        has_kpt_b = set()\n",
    "        for t, (i, j) in enumerate(zip(a_idx, b_idx)):\n",
    "            if i not in has_kpt_a and j not in has_kpt_b:\n",
    "                idx.append(t)\n",
    "                has_kpt_a.add(i)\n",
    "                has_kpt_b.add(j)\n",
    "        idx = np.asarray(idx, dtype=np.int32)\n",
    "        return a_idx[idx], b_idx[idx], affinity_scores[idx]\n",
    "\n",
    "    def group_keypoints(self, all_keypoints_by_type, pafs, pose_entry_size=20):\n",
    "        all_keypoints = np.concatenate(all_keypoints_by_type, axis=0)\n",
    "        pose_entries = []\n",
    "        # For every limb.\n",
    "        for part_id, paf_channel in enumerate(self.paf_indices):\n",
    "            kpt_a_id, kpt_b_id = self.skeleton[part_id]\n",
    "            kpts_a = all_keypoints_by_type[kpt_a_id]\n",
    "            kpts_b = all_keypoints_by_type[kpt_b_id]\n",
    "            n = len(kpts_a)\n",
    "            m = len(kpts_b)\n",
    "            if n == 0 or m == 0:\n",
    "                continue\n",
    "\n",
    "            # Get vectors between all pairs of keypoints, i.e. candidate limb vectors.\n",
    "            a = kpts_a[:, :2]\n",
    "            a = np.broadcast_to(a[None], (m, n, 2))\n",
    "            b = kpts_b[:, :2]\n",
    "            vec_raw = (b[:, None, :] - a).reshape(-1, 1, 2)\n",
    "\n",
    "            # Sample points along every candidate limb vector.\n",
    "            steps = 1 / (self.points_per_limb - 1) * vec_raw\n",
    "            points = steps * self.grid + a.reshape(-1, 1, 2)\n",
    "            points = points.round().astype(dtype=np.int32)\n",
    "            x = points[..., 0].ravel()\n",
    "            y = points[..., 1].ravel()\n",
    "\n",
    "            # Compute affinity score between candidate limb vectors and part affinity field.\n",
    "            part_pafs = pafs[0, :, :, paf_channel : paf_channel + 2]\n",
    "            field = part_pafs[y, x].reshape(-1, self.points_per_limb, 2)\n",
    "            vec_norm = np.linalg.norm(vec_raw, ord=2, axis=-1, keepdims=True)\n",
    "            vec = vec_raw / (vec_norm + 1e-6)\n",
    "            affinity_scores = (field * vec).sum(-1).reshape(-1, self.points_per_limb)\n",
    "            valid_affinity_scores = affinity_scores > self.min_paf_alignment_score\n",
    "            valid_num = valid_affinity_scores.sum(1)\n",
    "            affinity_scores = (affinity_scores * valid_affinity_scores).sum(1) / (valid_num + 1e-6)\n",
    "            success_ratio = valid_num / self.points_per_limb\n",
    "\n",
    "            # Get a list of limbs according to the obtained affinity score.\n",
    "            valid_limbs = np.where(np.logical_and(affinity_scores > 0, success_ratio > 0.8))[0]\n",
    "            if len(valid_limbs) == 0:\n",
    "                continue\n",
    "            b_idx, a_idx = np.divmod(valid_limbs, n)\n",
    "            affinity_scores = affinity_scores[valid_limbs]\n",
    "\n",
    "            # Suppress incompatible connections.\n",
    "            a_idx, b_idx, affinity_scores = self.connections_nms(a_idx, b_idx, affinity_scores)\n",
    "            connections = list(\n",
    "                zip(\n",
    "                    kpts_a[a_idx, 3].astype(np.int32),\n",
    "                    kpts_b[b_idx, 3].astype(np.int32),\n",
    "                    affinity_scores,\n",
    "                )\n",
    "            )\n",
    "            if len(connections) == 0:\n",
    "                continue\n",
    "\n",
    "            # Update poses with new connections.\n",
    "            pose_entries = self.update_poses(\n",
    "                kpt_a_id,\n",
    "                kpt_b_id,\n",
    "                all_keypoints,\n",
    "                connections,\n",
    "                pose_entries,\n",
    "                pose_entry_size,\n",
    "            )\n",
    "\n",
    "        # Remove poses with not enough points.\n",
    "        pose_entries = np.asarray(pose_entries, dtype=np.float32).reshape(-1, pose_entry_size)\n",
    "        pose_entries = pose_entries[pose_entries[:, -1] >= 3]\n",
    "        return pose_entries, all_keypoints\n",
    "\n",
    "    @staticmethod\n",
    "    def convert_to_coco_format(pose_entries, all_keypoints):\n",
    "        num_joints = 17\n",
    "        coco_keypoints = []\n",
    "        scores = []\n",
    "        for pose in pose_entries:\n",
    "            if len(pose) == 0:\n",
    "                continue\n",
    "            keypoints = np.zeros(num_joints * 3)\n",
    "            reorder_map = [0, -1, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3]\n",
    "            person_score = pose[-2]\n",
    "            for keypoint_id, target_id in zip(pose[:-2], reorder_map):\n",
    "                if target_id < 0:\n",
    "                    continue\n",
    "                cx, cy, score = 0, 0, 0  # keypoint not found\n",
    "                if keypoint_id != -1:\n",
    "                    cx, cy, score = all_keypoints[int(keypoint_id), 0:3]\n",
    "                keypoints[target_id * 3 + 0] = cx\n",
    "                keypoints[target_id * 3 + 1] = cy\n",
    "                keypoints[target_id * 3 + 2] = score\n",
    "            coco_keypoints.append(keypoints)\n",
    "            scores.append(person_score * max(0, (pose[-1] - 1)))  # -1 for 'neck'\n",
    "        return np.asarray(coco_keypoints), np.asarray(scores)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Processing\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "decoder = OpenPoseDecoder()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Process Results\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "A bunch of useful functions to transform results into poses.\n",
    "\n",
    "First, pool the heatmap. Since pooling is not available in numpy, use a simple method to do it directly with numpy. Then, use non-maximum suppression to get the keypoints from the heatmap. After that, decode poses by using the decoder. Since the input image is bigger than the network outputs, you need to multiply all pose coordinates by a scaling factor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2D pooling in numpy (from: https://stackoverflow.com/a/54966908/1624463)\n",
    "def pool2d(A, kernel_size, stride, padding, pool_mode=\"max\"):\n",
    "    \"\"\"\n",
    "    2D Pooling\n",
    "\n",
    "    Parameters:\n",
    "        A: input 2D array\n",
    "        kernel_size: int, the size of the window\n",
    "        stride: int, the stride of the window\n",
    "        padding: int, implicit zero paddings on both sides of the input\n",
    "        pool_mode: string, 'max' or 'avg'\n",
    "    \"\"\"\n",
    "    # Padding\n",
    "    A = np.pad(A, padding, mode=\"constant\")\n",
    "\n",
    "    # Window view of A\n",
    "    output_shape = (\n",
    "        (A.shape[0] - kernel_size) // stride + 1,\n",
    "        (A.shape[1] - kernel_size) // stride + 1,\n",
    "    )\n",
    "    kernel_size = (kernel_size, kernel_size)\n",
    "    A_w = as_strided(\n",
    "        A,\n",
    "        shape=output_shape + kernel_size,\n",
    "        strides=(stride * A.strides[0], stride * A.strides[1]) + A.strides,\n",
    "    )\n",
    "    A_w = A_w.reshape(-1, *kernel_size)\n",
    "\n",
    "    # Return the result of pooling.\n",
    "    if pool_mode == \"max\":\n",
    "        return A_w.max(axis=(1, 2)).reshape(output_shape)\n",
    "    elif pool_mode == \"avg\":\n",
    "        return A_w.mean(axis=(1, 2)).reshape(output_shape)\n",
    "\n",
    "\n",
    "# non maximum suppression\n",
    "def heatmap_nms(heatmaps, pooled_heatmaps):\n",
    "    return heatmaps * (heatmaps == pooled_heatmaps)\n",
    "\n",
    "\n",
    "# Get poses from results.\n",
    "def process_results(img, pafs, heatmaps):\n",
    "    # This processing comes from\n",
    "    # https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/models/open_pose.py\n",
    "    pooled_heatmaps = np.array([[pool2d(h, kernel_size=3, stride=1, padding=1, pool_mode=\"max\") for h in heatmaps[0]]])\n",
    "    nms_heatmaps = heatmap_nms(heatmaps, pooled_heatmaps)\n",
    "\n",
    "    # Decode poses.\n",
    "    poses, scores = decoder(heatmaps, nms_heatmaps, pafs)\n",
    "    output_shape = list(compiled_model.output(index=0).partial_shape)\n",
    "    output_scale = (\n",
    "        img.shape[1] / output_shape[3].get_length(),\n",
    "        img.shape[0] / output_shape[2].get_length(),\n",
    "    )\n",
    "    # Multiply coordinates by a scaling factor.\n",
    "    poses[:, :, :2] *= output_scale\n",
    "    return poses, scores"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Draw Pose Overlays\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Draw pose overlays on the image to visualize estimated poses. Joints are drawn as circles and limbs are drawn as lines. The code is based on the [Human Pose Estimation Demo](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos/human_pose_estimation_demo/python) from Open Model Zoo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "colors = (\n",
    "    (255, 0, 0),\n",
    "    (255, 0, 255),\n",
    "    (170, 0, 255),\n",
    "    (255, 0, 85),\n",
    "    (255, 0, 170),\n",
    "    (85, 255, 0),\n",
    "    (255, 170, 0),\n",
    "    (0, 255, 0),\n",
    "    (255, 255, 0),\n",
    "    (0, 255, 85),\n",
    "    (170, 255, 0),\n",
    "    (0, 85, 255),\n",
    "    (0, 255, 170),\n",
    "    (0, 0, 255),\n",
    "    (0, 255, 255),\n",
    "    (85, 0, 255),\n",
    "    (0, 170, 255),\n",
    ")\n",
    "\n",
    "default_skeleton = (\n",
    "    (15, 13),\n",
    "    (13, 11),\n",
    "    (16, 14),\n",
    "    (14, 12),\n",
    "    (11, 12),\n",
    "    (5, 11),\n",
    "    (6, 12),\n",
    "    (5, 6),\n",
    "    (5, 7),\n",
    "    (6, 8),\n",
    "    (7, 9),\n",
    "    (8, 10),\n",
    "    (1, 2),\n",
    "    (0, 1),\n",
    "    (0, 2),\n",
    "    (1, 3),\n",
    "    (2, 4),\n",
    "    (3, 5),\n",
    "    (4, 6),\n",
    ")\n",
    "\n",
    "\n",
    "def draw_poses(img, poses, point_score_threshold, skeleton=default_skeleton):\n",
    "    if poses.size == 0:\n",
    "        return img\n",
    "\n",
    "    img_limbs = np.copy(img)\n",
    "    for pose in poses:\n",
    "        points = pose[:, :2].astype(np.int32)\n",
    "        points_scores = pose[:, 2]\n",
    "        # Draw joints.\n",
    "        for i, (p, v) in enumerate(zip(points, points_scores)):\n",
    "            if v > point_score_threshold:\n",
    "                cv2.circle(img, tuple(p), 1, colors[i], 2)\n",
    "        # Draw limbs.\n",
    "        for i, j in skeleton:\n",
    "            if points_scores[i] > point_score_threshold and points_scores[j] > point_score_threshold:\n",
    "                cv2.line(\n",
    "                    img_limbs,\n",
    "                    tuple(points[i]),\n",
    "                    tuple(points[j]),\n",
    "                    color=colors[j],\n",
    "                    thickness=4,\n",
    "                )\n",
    "    cv2.addWeighted(img, 0.4, img_limbs, 0.6, 0, dst=img)\n",
    "    return img"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Main Processing Function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run pose estimation on the specified source. Either a webcam or a video file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main processing function to run pose estimation.\n",
    "def run_pose_estimation(source=0, flip=False, use_popup=False, skip_first_frames=0):\n",
    "    pafs_output_key = compiled_model.output(\"Mconv7_stage2_L1\")\n",
    "    heatmaps_output_key = compiled_model.output(\"Mconv7_stage2_L2\")\n",
    "    player = None\n",
    "    try:\n",
    "        # Create a video player to play with target fps.\n",
    "        player = utils.VideoPlayer(source, flip=flip, fps=30, skip_first_frames=skip_first_frames)\n",
    "        # Start capturing.\n",
    "        player.start()\n",
    "        if use_popup:\n",
    "            title = \"Press ESC to Exit\"\n",
    "            cv2.namedWindow(title, cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)\n",
    "\n",
    "        processing_times = collections.deque()\n",
    "\n",
    "        while True:\n",
    "            # Grab the frame.\n",
    "            frame = player.next()\n",
    "            if frame is None:\n",
    "                print(\"Source ended\")\n",
    "                break\n",
    "            # If the frame is larger than full HD, reduce size to improve the performance.\n",
    "            scale = 1280 / max(frame.shape)\n",
    "            if scale < 1:\n",
    "                frame = cv2.resize(frame, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)\n",
    "\n",
    "            # Resize the image and change dims to fit neural network input.\n",
    "            # (see https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001)\n",
    "            input_img = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)\n",
    "            # Create a batch of images (size = 1).\n",
    "            input_img = input_img.transpose((2, 0, 1))[np.newaxis, ...]\n",
    "\n",
    "            # Measure processing time.\n",
    "            start_time = time.time()\n",
    "            # Get results.\n",
    "            results = compiled_model([input_img])\n",
    "            stop_time = time.time()\n",
    "\n",
    "            pafs = results[pafs_output_key]\n",
    "            heatmaps = results[heatmaps_output_key]\n",
    "            # Get poses from network results.\n",
    "            poses, scores = process_results(frame, pafs, heatmaps)\n",
    "\n",
    "            # Draw poses on a frame.\n",
    "            frame = draw_poses(frame, poses, 0.1)\n",
    "\n",
    "            processing_times.append(stop_time - start_time)\n",
    "            # Use processing times from last 200 frames.\n",
    "            if len(processing_times) > 200:\n",
    "                processing_times.popleft()\n",
    "\n",
    "            _, f_width = frame.shape[:2]\n",
    "            # mean processing time [ms]\n",
    "            processing_time = np.mean(processing_times) * 1000\n",
    "            fps = 1000 / processing_time\n",
    "            cv2.putText(\n",
    "                frame,\n",
    "                f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n",
    "                (20, 40),\n",
    "                cv2.FONT_HERSHEY_COMPLEX,\n",
    "                f_width / 1000,\n",
    "                (0, 0, 255),\n",
    "                1,\n",
    "                cv2.LINE_AA,\n",
    "            )\n",
    "\n",
    "            # Use this workaround if there is flickering.\n",
    "            if use_popup:\n",
    "                cv2.imshow(title, frame)\n",
    "                key = cv2.waitKey(1)\n",
    "                # escape = 27\n",
    "                if key == 27:\n",
    "                    break\n",
    "            else:\n",
    "                # Encode numpy array to jpg.\n",
    "                _, encoded_img = cv2.imencode(\".jpg\", frame, params=[cv2.IMWRITE_JPEG_QUALITY, 90])\n",
    "                # Create an IPython image.\n",
    "                i = display.Image(data=encoded_img)\n",
    "                # Display the image in this notebook.\n",
    "                display.clear_output(wait=True)\n",
    "                display.display(i)\n",
    "    # ctrl-c\n",
    "    except KeyboardInterrupt:\n",
    "        print(\"Interrupted\")\n",
    "    # any different error\n",
    "    except RuntimeError as e:\n",
    "        print(e)\n",
    "    finally:\n",
    "        if player is not None:\n",
    "            # Stop capturing.\n",
    "            player.stop()\n",
    "        if use_popup:\n",
    "            cv2.destroyAllWindows()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Run Live Pose Estimation\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Use a webcam as the video input. By default, the primary webcam is set with `source=0`. If you have multiple webcams, each one will be assigned a consecutive number starting at 0. Set `flip=True` when using a front-facing camera. Some web browsers, especially Mozilla Firefox, may cause flickering. If you experience flickering, set `use_popup=True`.\n",
    "\n",
    "> **NOTE**: To use this notebook with a webcam, you need to run the notebook on a computer with a webcam. If you run the notebook on a server (for example, Binder), the webcam will not work. Popup mode may not work if you run this notebook on a remote computer (for example, Binder).\n",
    "\n",
    "If you do not have a webcam, you can still run this demo with a video file. Any [format supported by OpenCV](https://docs.opencv.org/4.5.1/dd/d43/tutorial_py_video_display.html) will work. You can skip first `N` frames to fast forward video.\n",
    "\n",
    "Run the pose estimation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "USE_WEBCAM = False\n",
    "cam_id = 0\n",
    "video_file = Path(\"store-aisle-detection.mp4\")\n",
    "video_url = \"https://storage.openvinotoolkit.org/data/test_data/videos/store-aisle-detection.mp4\"\n",
    "source = cam_id if USE_WEBCAM else video_file\n",
    "\n",
    "if not USE_WEBCAM and not Path(video_file).exists():\n",
    "    utils.download_file(video_url)\n",
    "\n",
    "additional_options = {\"skip_first_frames\": 500} if not USE_WEBCAM else {}\n",
    "run_pose_estimation(source=source, flip=isinstance(source, int), use_popup=False, **additional_options)"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit Metadata",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  },
  "openvino_notebooks": {
   "imageUrl": "https://user-images.githubusercontent.com/4547501/138267961-41d754e7-59db-49f6-b700-63c3a636fad7.gif",
   "tags": {
    "categories": [
     "Live Demos"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Pose Estimation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
